<template>
  <el-row :gutter="20">
    <el-col :span="12">
      <div class="el-descriptions__header">
        <div class="el-descriptions__title">对照点</div>
        <div>
          <el-space :size="20">
            <el-upload
              :show-file-list="false"
              :before-upload="handleChangePonits"
              accept=".xlsx, .xls"
            >
              <el-button type="primary" plain size="default">上传对照点xlsx</el-button>
            </el-upload>
            <el-button type="primary" @click="calculation" size="default">基线计算</el-button>
          </el-space>
        </div>
      </div>
      <el-table :data="pointsForm.table" border style="height: 280px">
        <el-table-column fixed="left" type="index" label="序号" width="80" align="center" />
        <el-table-column prop="点位" label="点位" width="120" align="center" />
        <template v-for="item in pointsForm.columns" :key="item">
          <el-table-column :prop="item" :label="item" min-width="120" align="center" />
        </template>
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleRemove(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-16px el-descriptions__header">
        <div class="el-descriptions__title">基线计算结果</div>
      </div>
      <el-table :data="resultForm.table" border style="height: 280px">
        <el-table-column prop="name" fixed="left" label="指标" min-width="120" align="center" />
        <el-table-column prop="normalDistr" label="是否符合正态分布" width="150" align="center">
          <template #default="scope">
            <span>{{
              scope.row.normalDistr ? '符合' : scope.row.normalDistr === false ? '不符合' : ''
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="notable" label="显著性" align="center" />
        <el-table-column prop="mean" label="算术平均值" width="110" align="center" />
        <el-table-column prop="deviation" label="标准差" align="center" />
        <el-table-column prop="line90" label="基线（90%参考值上限）" width="190" align="center" />
        <el-table-column prop="quantile" label="基线（90%分位数）" width="170" align="center" />
        <el-table-column prop="risk" fixed="right" label="风险控制值" width="160" align="center">
          <template #default="scope">
            <el-input size="default" v-model="scope.row.risk" />
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col :span="12">
      <div class="h-660px border-solid border-1 border-gray-300 border">
        <MyMap>
          <GeoTiff :data="formRecord.imagLayer" />
          <geo v-if="showMap" :data="formRecord.rangeLayer" :layer-style="featureStyle" />
          <geo :data="formRecord.linesLayer" :layer-style="lineStyle" />
          <MapMarker :data="comPints" :layer-style="pointsFun" @show="selectPoint" />
        </MyMap>
      </div>
    </el-col>
    <el-col :span="24" class="text-center mt-16px">
      <el-button @click="cancel">上一步</el-button>
      <el-button type="primary" :disabled="!showResult" @click="next">下一步</el-button>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import MyMap from '../map/map.vue'
import geo from '../map/geo'
import GeoTiff from '../map/geoTiff'
import MapMarker from '../map/marker'
import { lineStyle, pointsFun, featureStyle } from './style'
import type { FormType } from '../types'
import { excelToJson } from '@/utils/xlsx'
import { mathApi } from '@/api/appraisal/index'

defineOptions({ name: 'Step2Form' })

const message = useMessage()

const emits = defineEmits<{
  (e: 'next', data: any): void
  (e: 'cancel'): void
}>()

const { formRecord } = defineProps<{
  formRecord: FormType
}>()

const showMap = ref(false)
onMounted(() => {
  showMap.value = true
})

/**
 * 点位列表
 */
const pointsForm = reactive({
  table: [] as any,
  columns: [] as string[]
})

/**
 * 基线列表
 */
const showResult = ref(false)
const resultForm = reactive({
  table: [] as any
})

const init = () => {
  resultForm.table = formRecord.baseInfo.pollutantType.map((item: string) => {
    pointsForm.columns.push(item)
    return {
      name: item,
      risk: undefined
    }
  })
}
init()

const handleChangePonits = async (file) => {
  const data = await excelToJson(file)
  pointsForm.table = data
  return false
}
/**
 * 设置点位样式
 */
const comPints = computed(() => {
  const resultPoints = formRecord.poniosLayer.map((item) => {
    const inIN = pointsForm.table.find(
      (a) => a.X === item.coordinate[0] && a.Y === item.coordinate[1]
    )
    return {
      ...item,
      type: inIN ? 1 : 0
    }
  })
  return resultPoints
})

const selectPoint = (a) => {
  // 已存在则不再添加
  const isInlist = pointsForm.table.find(
    (item) => a.coordinate[0] === item.X && a.coordinate[1] === item.Y
  )
  if (isInlist) return
  // 获取点击的点
  const point = formRecord.baseInfo.surveyPoints.find(
    (item) => a.coordinate[0] === item.X && a.coordinate[1] === item.Y
  )
  pointsForm.table.push(point)
}

/**
 * 删除
 */
const handleRemove = (index) => {
  pointsForm.table.splice(index, 1)
}

const next = () => {
  let isValid = true
  resultForm.table.forEach((item) => {
    if (!item.risk || !/^\d+(\.\d+)?$/.test(item.risk)) {
      isValid = false
      return
    }
  })
  if (!isValid) {
    message.error('请输入正确的风险值')
    return
  }
  emits('next', {
    limit: resultForm.table
  })
}

const cancel = () => {
  emits('cancel')
}

/**
 * 基线计算
 */
const calculation = async () => {
  if (!pointsForm.table.length || pointsForm.table.length < 5) {
    message.error('请上传对照点,至少5个点')
    return
  }
  const obj = {}
  resultForm.table.forEach((key) => {
    obj[key.name] = pointsForm.table.map((item) => {
      return Number(item[key.name])
    })
  })
  const data = await mathApi(obj)
  resultForm.table = resultForm.table.map((item) => {
    return {
      name: item.name,
      ...data[item.name],
      risk: item.risk
    }
  })
  showResult.value = true
}
</script>
